package com.qianwei.footpath.net;

import android.webkit.WebSettings;

import androidx.annotation.NonNull;

import com.common.baselib.log.LogUtils;
import com.common.baselib.utils.CommonUtils;
import com.common.baselib.utils.NetworkUtils;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

public class XInterceptor {
    /**
     * 自定义的，重试N次的拦截器
     * 通过：addInterceptor 设置
     */
    public static class Retry implements Interceptor {

        public int maxRetry;//最大重试次数
        private int retryNum = 0;//假如设置为3次重试的话，则最大可能请求4次（默认1次+3次重试）

        public Retry(int maxRetry) {
            this.maxRetry = maxRetry;
        }

        @Override
        public Response intercept(@NonNull Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
            LogUtils.i("Retry num:" + retryNum);
            while (!response.isSuccessful() && retryNum < maxRetry) {
                retryNum++;
                LogUtils.i("Retry num:" + retryNum);
                response = chain.proceed(request);
            }
            return response;
        }
    }

    /**
     * 设置没有网络的情况下，
     * 的缓存时间
     * 通过：addInterceptor 设置
     */
    public static class CommonNoNetCache implements Interceptor {

        private int maxCacheTimeSecond = 0;

        public CommonNoNetCache(int maxCacheTimeSecond) {
            this.maxCacheTimeSecond = maxCacheTimeSecond;
        }

        @Override
        public Response intercept(@NonNull Chain chain) throws IOException {
            Request request = chain.request();
            if (!NetworkUtils.isConnected(CommonUtils.getApp())) {
                CacheControl tempCacheControl = new CacheControl.Builder()
                        .onlyIfCached()
                        .maxStale(maxCacheTimeSecond, TimeUnit.SECONDS)
                        .build();
                request = request.newBuilder()
                        .cacheControl(tempCacheControl)
                        .build();
            }
            return chain.proceed(request);
        }
    }

    /**
     * 设置在有网络的情况下的缓存时间
     * 在有网络的时候，会优先获取缓存
     * 通过：addNetworkInterceptor 设置
     */
    public static class CommonNetCache implements Interceptor {

        private int maxCacheTimeSecond = 0;

        public CommonNetCache(int maxCacheTimeSecond) {
            this.maxCacheTimeSecond = maxCacheTimeSecond;
        }

        @Override
        public Response intercept(@NonNull Chain chain) throws IOException {
            Request request = chain.request();
            Response originalResponse = chain.proceed(request);
            return originalResponse.newBuilder()
                    .removeHeader("Pragma")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", "public, max-age=" + maxCacheTimeSecond)
                    .build();
        }
    }

    /**
     * 设置一个日志打印拦截器
     * 通过：addInterceptor 设置
     */
    public static class CommonLog implements Interceptor {

        public CommonLog() {
        }

        @Override
        public Response intercept(@NonNull Chain chain) throws IOException {

            Request request = chain.request();
            long t1 = System.currentTimeMillis();//请求发起的时间
            Response response = chain.proceed(request);
            long t2 = System.currentTimeMillis();//收到响应的时间

            //这里不能直接使用response.body().string()的方式输出日志
            //因为response.body().string()之后，response中的流会被关闭，程序会报错，我们需要创建出一
            //个新的response给应用层处理
//            ResponseBody responseBody = response.peekBody(1024 * 1024);
//            Object responseResult = responseBody.string();
//            LogUtils.i("-------Response信息如下------\n URL:" + response.request().url() + " \n use-timeMs: " + (t2 - t1) + " \n data: " + responseResult);

            return response;
        }
    }

    /**
     * 设置一个添加header拦截器
     * 通过：addInterceptor 设置
     */
    public static class CommonHeader implements Interceptor {

        @NotNull
        @Override
        public Response intercept(@NotNull Chain chain) throws IOException {
            Request request = chain.request()
                    .newBuilder()
//                    .addHeader("locationId", LocalCacheDataManage.getLocationId())
//                    .addHeader("projectCode", LocalCacheDataManage.getProjectCode())
                    .removeHeader("User-Agent")
                    .addHeader("User-Agent", WebSettings.getDefaultUserAgent(CommonUtils.getApp()))
                    .build();
            return chain.proceed(request);
        }
    }

}
